package cn.wowjoy.office.materialmanage.materialdetail;

import android.arch.lifecycle.MediatorLiveData;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;

import com.google.gson.Gson;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

import cn.wowjoy.office.base.BaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.SetGoodsJsonRequest;
import cn.wowjoy.office.data.response.GoodsDetailResponse;
import cn.wowjoy.office.data.response.StaffListResponse;
import cn.wowjoy.office.data.response.StockDetailListResponse;
import cn.wowjoy.office.data.response.StockDetailResponse;
import cn.wowjoy.office.utils.ImageFileParse;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.ToastUtil;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

import static cn.wowjoy.office.data.constant.Constants.MEDIA_TYPE_JSON;

/**
 * Created by Sherily on 2017/11/1.
 */

public class MaterialDetialViewModel extends NewBaseViewModel {
    @Inject
    public MaterialDetialViewModel(@NonNull NewMainApplication application) {
        super(application);
    }
    @Inject
    ApiService apiService;

    @Inject
    PreferenceManager preferenceManager;

    @Override
    public void onCreateViewModel() {

    }


    public MediatorLiveData<LiveDataWrapper<GoodsDetailResponse>> getDetail(String code){
        final MediatorLiveData<LiveDataWrapper<GoodsDetailResponse>> goodsResponse = new MediatorLiveData<>();
        goodsResponse.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getGoodsDetailInfo(code,null)
                .flatMap(new ResultDataParse<GoodsDetailResponse>())
                .compose(new RxSchedulerTransformer<GoodsDetailResponse>())
                .subscribe(new Consumer<GoodsDetailResponse>() {
                               @Override
                               public void accept(GoodsDetailResponse response) throws Exception {
//                                   waitDialog.dismiss();
//                                   materialDetailActivity.setModel(response);
                                   goodsResponse.setValue(LiveDataWrapper.success(response));
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
//                                waitDialog.dismiss();
//                                new MyToast(materialDetailActivity).showinfo(throwable.getMessage());
//                                materialDetailActivity.handleException(throwable,true);
                                goodsResponse.setValue(LiveDataWrapper.error(throwable,null));

                            }
                        });
        addDisposable(disposable);
        return goodsResponse;
    }


    public MediatorLiveData<LiveDataWrapper<StockDetailListResponse>> getStockDetailList(String code){
        final MediatorLiveData<LiveDataWrapper<StockDetailListResponse>> stockList = new MediatorLiveData<>();
        stockList.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getStockDetailList(code)
                .flatMap(new ResultDataParse<StockDetailListResponse>())
                .compose(new RxSchedulerTransformer<StockDetailListResponse>())
                .subscribe(new Consumer<StockDetailListResponse>() {
                               @Override
                               public void accept(StockDetailListResponse stockDetailListResponse) throws Exception {
                                   stockList.setValue(LiveDataWrapper.success(stockDetailListResponse));
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                stockList.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);
        return stockList;
    }
    //    private String smallPath;
    private List<String> imges = new ArrayList<>();
    private File createTempFile(String filePath) {
        String timeStamp = new SimpleDateFormat("MMddHHmmss", Locale.CHINA).format(new Date());
        String externalStorageState = Environment.getExternalStorageState();
        File dir = new File(Environment.getExternalStorageDirectory() + filePath);
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            if (!dir.exists()) {
                dir.mkdirs();
            }
            return new File(dir, timeStamp + ".png");
        } else {
            File cacheDir = getApplication().getApplicationContext().getCacheDir();
            return new File(cacheDir, timeStamp + ".png");
        }
    }

    private Map<String, RequestBody> initSaveInfo(String goodsCode, String barCode, List<String> filePaths){
        Gson gson = new Gson();

        Map<String, RequestBody> bodyMap = new ArrayMap<>();
        SetGoodsJsonRequest request = new SetGoodsJsonRequest(goodsCode,barCode);
        RequestBody bodyJson = RequestBody.create(MEDIA_TYPE_JSON, gson.toJson(request));
        bodyMap.put("goods", bodyJson);
        bodyMap = ImageFileParse.typeTurn(filePaths,bodyMap,"file");
        return bodyMap;

    }
    public MediatorLiveData<LiveDataWrapper<ResultEmpty>> saveInfo(String goodsCode,String barCode,List<String> filePaths){
//        waitDialog = CreateDialog.waitingDialog(materialDetailActivity);
        final MediatorLiveData<LiveDataWrapper<ResultEmpty>> saveResult = new MediatorLiveData<>();
        saveResult.setValue(LiveDataWrapper.loading(null));
        Map<String, RequestBody> bodyMap = initSaveInfo(goodsCode,barCode,filePaths);
        Disposable disposable = apiService.setGoods(bodyMap)
                .flatMap(new ResultDataParse<ResultEmpty>())
                .compose(new RxSchedulerTransformer<ResultEmpty>())
                .subscribe(new Consumer<ResultEmpty>() {
                               @Override
                               public void accept(ResultEmpty resultEmpty) throws Exception {
//                                   waitDialog.dismiss();
                                   ToastUtil.toastImage(getApplication().getApplicationContext(),"提交成功",-1);
//                                   materialDetailActivity.setSaveStatus();
                                   saveResult.setValue(LiveDataWrapper.success(null));

                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
//                                waitDialog.dismiss();
//                                materialDetailActivity.handleException(throwable,false);
//                                new MyToast(materialDetailActivity).showinfo(throwable.getMessage());
                                saveResult.setValue(LiveDataWrapper.error(throwable,null));

                            }
                        });
        addDisposable(disposable);
        return saveResult;
    }

}

